﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    
<!--
// // -------------------------------------------------------------------------------------
// // Copyright 2012 ELEN7046 Group 2
// // 
// // Last Modified on: 2012-06-10
// // 
// // Contributors:
// // 
// // Amith Sewnarain
// // Elmar Vosloo
// // Jason Thorne
// // Satish Jewan
// // 
// // Wits University 
// // School of Electrical & Information Engineering
// // Software Engineering Tools and Techniques
// // 
// // -------------------------------------------------------------------------------------
// // 
// // This file is part of the DishDash Event Visualization System.
// // 
// // DishDash is free software: you can redistribute it and/or modify
// // it under the terms of the GNU General Public License as published by
// // the Free Software Foundation, either version 3 of the License, or
// // (at your option) any later version.
// // 
// // DishDash is distributed in the hope that it will be useful,
// // but WITHOUT ANY WARRANTY; without even the implied warranty of
// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// // GNU General Public License for more details.
// // 
// // You should have received a copy of the GNU General Public License
// // along with DishDash.  
// // If not, see <http://www.gnu.org/licenses/>.
// // -------------------------------------------------------------------------------------
-->
    <head>
        <title></title>
        <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script src="js/jquery-1.6.2.min.js" type="text/javascript"> </script>
        <script src="js/bootstrap.min.js" type="text/javascript"> </script>
        <script src="js/knockout-1.2.1.js" type="text/javascript"> </script>
        <script src="services/LookUpClientSideService.js" type="text/javascript"> </script>
        <script src="services/EventFetchingClientSideService.js" type="text/javascript"> </script>
        <script src="js/dishdash.widgetconfiguration.js" type="text/javascript"> </script>

    
    </head>
    <body>
        <div class="navbar">
            <div class="navbar-inner">
                <div class="container">
                    <a class="brand" href="#">Dish Dash</a>
                    <ul class="nav">
                        <li class="active"><a href="#">Add or Edit a Widget</a></li>
                    </ul>
                </div>
            </div>
        </div>
        <div id="Add Widget" style="visibility: visible">
     
            <div class="span8">
                <fieldset>
                    <legend>Add Widget</legend>
                    <div class="control-group">
                        <label class="control-label">Widget Name
                        </label>
                        <div class="controls">
                            <input id="Widget Name" type="text" class="input-xlarge" />
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Widget Type
                        </label>
                        <div class="controls">
                            <input id="radioWidgetTypeLineGraph" type="radio" name="WidgetType" value="1"  onclick=" displayWidgetTypeDiv(); ">Line Graph
                            <input id="radioWidgetTypeAggregatedEventCount" type="radio" name="WidgetType"  value="2" onclick=" displayWidgetTypeDiv(); ">Aggregated Event Count
                            <input id="radioWidgetTypeEventDistribution" type="radio" name="WidgetType" value="3" onclick=" displayWidgetTypeDiv(); "   >Event Distribution
                   
                        </div>
                    </div>
            
                    <div class="control-group">
                        <label class="control-label">
                            Events
                        </label>
                        <div style="border-width: 2px; border-style: solid; border-color: #dddddd;">
                            <div class="controls">
                                <select id="Events" data-bind="options: categoryValues">
                                </select>
                                <button class="btn btn-primary" onclick=" addCategoryRow('dataTable'); ">
                                    +</button>
                            </div>
                            <div>
                                <table id="dataTable" width="350px" border="1">
                                </table>
                            </div>
                        </div>
                    </div>

                    <div id="divMeasurements" class="controls"  style="visibility: hidden">
                        <label class="control-label">
                            Measurements
                        </label>
                        <select id="Measurement" data-bind="options: measurementValues">
                        </select>
                
                        <!--<button class="btn btn-primary" onclick="addWidget();">
                                +</button>-->
                
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            Sampling Period</label>
                        <div class="controls">
                            <select id="Sampling Period" data-bind="options: samplingPeriodValues" ></select>                
                        </div>                
                    </div>

                    <div id="divPrecisions" class="control-group"  style="visibility: hidden">
                        <label class="control-label">
                            Precisions</label>
                        <div class="controls">
                            <select id="Precision" data-bind="options: precisionValues" ></select>                
                        </div>                
                    </div>

                    <div class="control-group">
                        <label class="control-label">
                            Refresh Time</label>
                        <div class="controls">
                            <select id="Refresh Time" data-bind="options: refreshTimeValues" ></select>                
                        </div>                
                    </div>       
                    <div id="divContexts" class="control-group" style="visibility: hidden">
                        <table>
                            <tr> <td>
                                     <div class="control-group">
                                         <label class="control-label">
                                             Context Name
                                         </label>
                                         <div class="controls">
                                             <input id="ContextKey" type="text" class="input-xlarge" />
                                         </div>
                                     </div>
                                 </td>
                                <td>
                                    <div class="control-group">
                                        <label class="control-label">
                                            Context Value 
                                        </label>
                                        <div class="controls">
                                            <input id="ContextValue" type="text" class="input-xlarge" />
                                        </div>
                                    </div>
            
                                </td>   
                            </tr>  
                        </table> </div> 
                    <div id="divGraphType" class="control-group" style="visibility: hidden">
                        <div class="control-group">
                            <label class="control-label">
                                Graph Type 
                            </label>
                            <div class="controls">
                                <select id="selectGraphType">
                                    <option value="0"></option>
                                    <option value="1">Stacked Bar</option>
                                    <option value="2">Radar</option>
                                </select>                
                            </div> 
                        </div>
               
                    </div>                           

                </fieldset>
            </div>
        </div>
        <div class="span6">
            <button id="SaveButton" class="btn btn-primary" onclick=" addWidget(); ">Save Widget</button>
            <button class="btn btn-primary" onclick=" cancel(); ">
                Cancel</button>
        </div>
   

        <script type="text/javascript">

            delRow = function(rowID) {
                var table = document.getElementById('dataTable');
                table.deleteRow(rowID);
            };
            addCategoryRow = function(tableID) {
                var select_list_field = document.getElementById('Events');
                var select_list_selected_index = select_list_field.selectedIndex;

                var text = select_list_field.options[select_list_selected_index].text;
                var value = select_list_field.value;

                addRowData('dataTable', value);
            };
            addRowData = function(tableID, value) {

                if (value == "") {
                    alert("Please select a valid category.");
                    return;
                }

                var table = document.getElementById(tableID);

                var rowCount = table.rows.length;
                var row = table.insertRow(rowCount);
                var cell1 = row.insertCell(0);
                cell1.innerHTML = value;

                var cell2 = row.insertCell(1);

                var minusButton = document.createElement('input');
                minusButton.type = "button";
                minusButton.value = "-";
                minusButton.className = "btn btn-primary";
                minusButton.id = rowCount;

                minusButton.onclick = function() {
                    delRow('' + minusButton.id + '');
                };
                cell2.appendChild(minusButton);
            };
            if (typeof(Storage) !== "undefined") {
                // Browser does support local storage
            } else {
                // No local storage support
                alert("Your browser does NOT support local storage. Any changes to the Dish Dash configuration will not be saved between browser sessions.");
            }

            function checkAddOrEditWidget() {
                var existingOrNewWidget = getURLParameter("WidgetName", false); //getURLParameter("WidgetName");

                if (existingOrNewWidget != null) {
                    var editWidget = dishdash.widgetconfiguration.getAWidget(existingOrNewWidget);
                    if (editWidget != null) {
                        document.getElementById("Widget Name").value = editWidget.widgetName;
                        document.getElementById("Measurement").selectedIndex = getMeasurementValueIndex(editWidget.measurement);
                        document.getElementById("Sampling Period").selectedIndex = getSamplingValueIndex(editWidget.samplePeriod);
                        document.getElementById("Precision").selectedIndex = getPrecisionValueIndex(editWidget.precision);
                        document.getElementById("Refresh Time").selectedIndex = getRefreshValueIndex(editWidget.refreshPeriod);
                        document.getElementById("ContextKey").value = editWidget.ContextKey;
                        document.getElementById("ContextValue").value = editWidget.ContextValue;
                        document.getElementById("selectGraphType").selectedIndex = editWidget.GraphType;


                        //Now check the Widget Type
                        if (editWidget.WidgetType == dishdash.widgetconfiguration.WidgetTypeEnum.LineGraph) {
                            radioLineGraph = document.getElementById("radioWidgetTypeLineGraph");
                            radioLineGraph.checked = true;


                        } else if (editWidget.WidgetType == dishdash.widgetconfiguration.WidgetTypeEnum.AggrEventCount) {
                            radioAggrCount = document.getElementById("radioWidgetTypeAggregatedEventCount");
                            radioAggrCount.checked = true;

                        } else if (editWidget.WidgetType == dishdash.widgetconfiguration.WidgetTypeEnum.EventDist) {
                            radioAggrEventDist = document.getElementById("radioWidgetTypeEventDistribution");
                            radioAggrEventDist.checked = true;
                        }
                        displayWidgetTypeDiv();

                        //Now add the existing events
                        if (editWidget.events != null) {
                            for (var i = 0; i < editWidget.events.length; i++) {
                                addRowData('dataTable', editWidget.events[i]);
                            }
                        }

                    } else {
                        alert("Error retrieving widget configuration from local storage");
                    }
                }
            }

            function displayWidgetTypeDiv() {
                //display the divs required for the required Widget Type
                //1. For the Line graph we require
                // 
                // Events
                // Sampling Period
                // Refresh Time
                // Only required for Line Graph
                // divMeasurements
                // divPrecisions
                //
                //2. For the Aggregated Event Count
                // 
                // Events
                // Sampling Period
                // Refresh Time
                // 
                //
                //3. For the Event Distribution
                // 
                // 
                // Events
                // Sampling Period
                // Refresh Time
                // Only required for Events
                //  Context Key   divContexts
                //  Context Value divContexts
                //  Graph Type - 1= Stacked Bar, 2 = Radar divGraphType

                radioLineGraph = document.getElementById("radioWidgetTypeLineGraph");
                radioAggrCount = document.getElementById("radioWidgetTypeAggregatedEventCount");
                radioAggrEventDist = document.getElementById("radioWidgetTypeEventDistribution");

                divMeasurements = document.getElementById("divMeasurements");
                divPrecisions = document.getElementById("divPrecisions");
                divContexts = document.getElementById("divContexts");
                divGraphType = document.getElementById("divGraphType");

                if (radioLineGraph.checked) {
                    divMeasurements.style.visibility = "visible";
                    divPrecisions.style.visibility = "visible";
                    divContexts.style.visibility = "hidden";
                    divGraphType.style.visibility = "hidden";

                } else if (radioAggrEventDist.checked) {
                    divContexts.style.visibility = "visible";
                    divGraphType.style.visibility = "visible";
                    divMeasurements.style.visibility = "hidden";
                    divPrecisions.style.visibility = "visible";
                } else {
                    divMeasurements.style.visibility = "hidden";
                    divPrecisions.style.visibility = "hidden";
                    divContexts.style.visibility = "hidden";
                    divGraphType.style.visibility = "hidden";
                }


            }

            function getCategoryValueIndex(strCategories) {
                for (var i = 0; i < viewModel.categoryValues.length; i++) {
                    if (viewModel.categoryValues[i] === strCategories) {
                        return i;
                    }
                }
            }

            function getMeasurementValueIndex(strMeasurement) {
                for (var i = 0; i < viewModel.lookUpValues.Measurements.length; i++) {
                    if (viewModel.lookUpValues.Measurements[i] === strMeasurement) {
                        return i;
                    }
                }
            }

            function getSamplingValueIndex(strSampling) {
                for (var i = 0; i < viewModel.lookUpValues.SamplingPeriodInSeconds.length; i++) {
                    if (viewModel.lookUpValues.SamplingPeriodInSeconds[i] === strSampling) {
                        return i;
                    }
                }
            }

            function getPrecisionValueIndex(strPrecision) {
                for (var i = 0; i < viewModel.lookUpValues.Precisions.length; i++) {
                    if (viewModel.lookUpValues.Precisions[i] === strPrecision) {
                        return i;
                    }
                }
            }

            function getRefreshValueIndex(strRefresh) {
                for (var i = 0; i < viewModel.lookUpValues.RefreshTimeInSeconds.length; i++) {
                    if (viewModel.lookUpValues.RefreshTimeInSeconds[i] === strRefresh) {
                        return i;
                    }
                }
            }

            function getURLParameter(name, url) { // optionally pass an URL to parse
                if (!url) url = window.location.href; // if no parameter url is given, use the page URL
                name = name.replace( /[\[]/ , "\\\[").replace( /[\]]/ , "\\\]"); // instruction needed if we want to extract an array
                var results = new RegExp("[\\?&]" + name + "=([^&#]*)").exec(url);
                if (results == null) return null; 								// if the name is not found, return null
                else // decodeURIComponent doesn't recognize '+' as encoding for space
                    return decodeURIComponent(results[1].replace( /\+/g , " "));
            }


            addWidget = function() {
                try {
                    //If localStorage supports with the browser
                    if (localStorage) {

                        var event1 = new Array();
                        var table = document.getElementById("dataTable");
                        for (var i = 0, row; row = table.rows[i]; i++) {
                            event1.push(row.cells[0].innerHTML);
                        }


                        var w = new dishdash.widgetconfiguration.Widget();

                        w.widgetName = document.getElementById("Widget Name").value;
                        w.events = event1;
                        w.measurement = document.getElementById("Measurement").value;
                        w.samplePeriod = document.getElementById("Sampling Period").value;
                        w.precision = document.getElementById("Precision").value;
                        w.refreshPeriod = document.getElementById("Refresh Time").value;
                        w.ContextKey = document.getElementById("ContextKey").value;
                        w.ContextValue = document.getElementById("ContextValue").value;
                        w.GraphType = document.getElementById("selectGraphType").value;

                        radioLineGraph = document.getElementById("radioWidgetTypeLineGraph");
                        radioAggrCount = document.getElementById("radioWidgetTypeAggregatedEventCount");
                        radioAggrEventDist = document.getElementById("radioWidgetTypeEventDistribution");

                        w.WidgetType = document.getElementById("selectGraphType").value;

                        if (radioLineGraph.checked) {
                            w.WidgetType = 1;
                        } else if (radioAggrCount.checked) {
                            w.WidgetType = 2;
                        } else if (radioAggrEventDist.checked) {
                            w.WidgetType = 3;

                        } else {
                            alert("Please select a widget type.");
                            return;
                        }

                        if (w.widgetName == "") {
                            alert("Please select a widget name.");
                            return;
                        }

                        if (w.events == "") {
                            alert("Please select a category.");
                            return;
                        }

                        dishdash.widgetconfiguration.saveAWidget(w);
                        alert("The follow widget has been successfully added: " + "\n" +
                            "Widget Name: " + "\"" + w.widgetName + "\"" + "\n" +
                            "\t" + "- Sampling Period: " + w.samplePeriod + "\n" +
                            "\t" + "- Precision: " + w.precision + "\n" +
                            "\t" + "- Refresh Period: " + w.refreshPeriod + " Second(s)" + "\n" +
                            "\t" + "- Event(s): " + w.events + "\n" +
                            "\t" + "- Measurement: " + w.measurement + "\n" +
                            "\t" + "- ContextKey: " + w.ContextKey + "\n" +
                            "\t" + "- ContextValue: " + w.ContextValue + "\n" +
                            "\t" + "- GraphType: " + w.GraphType + "\n" +
                            "\t" + "- WidgetType: " + w.WidgetType
                        );
                        window.close();
                    }
                } catch(err) {
                    alert(err.Description);
                }
            };

            window.onunload = function() {
                if (window.opener && !window.opener.closed) {
                    window.opener.popUpClosed();
                }
            };

            cancel = function() {
                window.close();
            };

            var viewModel = {
                lookUpValues: new Array(),
                categoryValues: ko.observableArray([]),
                widgetName: ko.observable(),
                measurementValues: ko.observableArray([]),
                precisionValues: ko.observableArray([]),
                samplingPeriodValues: ko.observableArray([]),
                refreshTimeValues: ko.observableArray([]),

                service: new dishdash.services.LookUpClientSideService(),

                getLookups: function() {
                    service = new dishdash.services.LookUpClientSideService();
                    service.GetAllLookUps(viewModel.getLookUpsCallback);
                },

                getLookUpsCallback: function(response) {
                    viewModel.lookUpValues = response;
                    viewModel.measurementValues(response.Measurements);
                    viewModel.measurementValues.splice(0, 0, "");
                    document.getElementById("Measurement").selectedIndex = 0;
                    viewModel.samplingPeriodValues(response.SamplingPeriodInSeconds);
                    viewModel.samplingPeriodValues.splice(0, 0, "");
                    document.getElementById("Sampling Period").selectedIndex = 0;
                    viewModel.precisionValues(response.Precisions);
                    viewModel.precisionValues.splice(0, 0, "");
                    document.getElementById("Precision").selectedIndex = 0;
                    viewModel.refreshTimeValues(response.RefreshTimeInSeconds);
                    viewModel.refreshTimeValues.splice(0, 0, "");
                    document.getElementById("Refresh Time").selectedIndex = 0;
                    checkAddOrEditWidget();
                },

                service: new dishdash.services.EventFetchingClientSideService(),

                getCategories: function() {
                    service = new dishdash.services.EventFetchingClientSideService();
                    service.GetAllCategories(viewModel.getCategoriesCallback);
                },

                getCategoriesCallback: function(response) {

                    viewModel.categoryValues(response.Categories);
                    viewModel.categoryValues.splice(0, 0, "");
                    document.getElementById("Events").selectedIndex = 0;
                }
            };

            viewModel.getLookups();
            viewModel.getCategories();

            ko.applyBindings(viewModel);

        </script>
    </body>
</html>
